/*
    @巡访日历控件
    @by jiangwei
    @options:{
        calendarType: noraml/week/month  月历/星期/单月
        multiSelect: true/false  是否支持多选
        initDate: Array  初始化数据,
        scheduleDate:Array 日程数据,
        userId:负责人ID
    }
    @method
        getSelectedData: 获取选择的日期数组

    @data format
        normal 'YYYY-MM-DD'   eg. '2015-06-02'
        week   1~7            eg. 星期一 => 1
        month  1~31           eg. 21


    require('page/js/frame/leftmenu/ambassadorCalendarCtrl');
    contentElem.ambassadorCalendarCtrl({calendarType:'normal',multiSelect:false});

    contentElem.ambassadorCalendarCtrl({calendarType:'week',multiSelect:true});

    contentElem.ambassadorCalendarCtrl({calendarType:'month',initDate:[12,13]});

    //console.log(contentElem.ambassadorCalendarCtrl('getSelectedDate'));

*/
define(function(require, exports, module) {
    'use strict';
    
    var rk = require('rk');
    


    $.datepicker.constructor.prototype._markDatepicker = function(container, arDates) {
        var $cont = $(container),
            $tb = $cont.find('table.ui-datepicker-calendar');
        $cont.find('table.ui-datepicker-calendar').find('td span.circle').remove();
        if (arDates){
            $.each(arDates, function(i, d) {
                var $td = $tb.find('td[data-year="' + d.getFullYear() + '"][data-month="' + d.getMonth() + '"]');
                $td = $td.find('a').filter(function() {
                    return parseInt($(this).text(), 10) == d.getDate();
                }).parent();
                $td.size() && $td.addClass('ui-datepicker-marked') && $td.append('<span class="circle"></span>');
            });
        }
    };

    var weekMap = ['','星期一','星期二','星期三','星期四','星期五','星期六','星期日'];

    $.widget( "rk.ambassadorCalendarCtrl", {
        options:{
            calendarType: 'normal', // normal, week , month
            initDate:null,
            schedulteDate:null,
            multiSelect:true,
            userId:0
        },
        _selectedDate: [],
        _scheduleDate:[],
        _create: function(){
            var me = this;

            me.destory();
        },
        _init:function(){
            var me = this;
            var opt = this.options;
            me._selectedDate = [];
            me._scheduleDate = [];
            if(opt.initDate){
                me._selectedDate = opt.initDate;
            }
            if(opt.schedulteDate){
                for(var i=0;i<opt.schedulteDate.length ; i++){
                    me._scheduleDate.push(new Date(opt.schedulteDate[i]));
                }
            }

            switch(opt.calendarType){
                case "normal": me._renderCalender();break;
                case "week": me._renderWeek();break;
                case "month":me._renderMonth();break;
                default:break;
            }
        },
        getSelectedDate: function(){
            var me = this;

            return me._selectedDate;
        },
        _renderCalender:function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            elem.append('<div class="schedule-datepicker-select-date"><span>计划将于</span><span act="select-date"></span><span>执行</span></div>') ;
            elem.append('<div class="schedule-datepicker-header" act="dayheader"><a act="datePre" href="javascript:;" class="pre" viewType="day"><span></span> </a><span class="date-content"><span act="headyear" class="date-year"></span><span act="headmonth" class="date-month"></span></span><a act="dateNext" href="javascript:;" class="next" viewType="day"><span></span></a></div>') ;
            elem.append('<div act="ambassadorDatePicker" class="ambassador-datepicker"></div>');
            var scheduleDatePicker = elem.find('div[act=ambassadorDatePicker]');
            //初始化日历控件
            scheduleDatePicker.datepicker({
                showOtherMonths: true,
                selectOtherMonths: true,
                changeMonth: true,
                changeYear: true,
                gotoCurrent: true,
                //minDate: new Date(),
                beforeShowDay: function(date){
                    var theDay = moment(date).format("YYYY-MM-DD");
                    return [true,$.inArray(theDay,me._selectedDate) >= 0?"ui-state-selected":''];
                },
                onSelect:function(dateText){
                    if(moment(dateText).isAfter(moment(new Date())) || dateText === moment(new Date()).format('YYYY-MM-DD')){
                        var index = $.inArray(dateText, me._selectedDate);
                        if(index >= 0){
                            me._selectedDate.splice(index,1);
                            scheduleDatePicker.datepicker('setDate','');
                        }else{
                            if( opt.multiSelect || me._selectedDate.length < 1){
                                me._selectedDate.push(dateText);

                                me._selectedDate = me._selectedDate.sort(function(a,b){
                                    return moment(a).isAfter(b);
                                });
                            }else if(!opt.multiSelect){
                                me._selectedDate = [];
                                me._selectedDate.push(dateText);
                            }
                        }
                    }else{
                        scheduleDatePicker.datepicker('setDate','');
                    }
                    setTimeout(function(){
                        scheduleDatePicker.datepicker('mark', me._scheduleDate);
                    }, 1);

                    me._renderSelectedTips();
                }   
            });


            if(opt.schedulteDate){
                setTimeout(function(){
                        scheduleDatePicker.datepicker('mark', me._scheduleDate);
                }, 1);
            }

            elem.find('a[act="datePre"]').click(function(){
                var prev_Date = moment(me._calendarNowDate).add(-1, 'month').format('YYYY-MM-DD');
                if(moment(prev_Date).format('M') < moment(new Date()).format('M')){
                    return;
                }
                me._calendarNowDate = prev_Date;
                me._renderCalenderHeader();
            });

            elem.find('a[act="dateNext"]').click(function(){
                me._calendarNowDate = moment(me._calendarNowDate).add(1, 'month').format('YYYY-MM-DD');
                me._renderCalenderHeader();
            });

            if(opt.initDate){
                var sortArray = opt.initDate.sort(function(a,b){
                    return moment(a).isBefore(b);
                });
                me._calendarNowDate = sortArray[0];
            }else{
                me._calendarNowDate = moment().format('YYYY-MM-DD');
            }
            elem.find('.schedule-datepicker-select-date').hide();
            me._renderCalenderHeader();
            me._renderSelectedTips();
        },
        _renderCalenderHeader: function(){
            var me = this;
            var elem = me.element;
            var opt = me.options;

            elem.find('.date-year').text(moment(me._calendarNowDate).format('YYYY') + '年');
            elem.find('.date-month').text(moment(me._calendarNowDate).format('MM') + '月');
            elem.find('div[act=ambassadorDatePicker]').datepicker('setDate',me._calendarNowDate);


            var firstDay_td = elem.find('td:first');
            var lastDay_td = elem.find('td:last');

            rk.post('/json/crm_schedule/count-by-day.action', {
                //startDate: moment(firstDay_td.attr('data-year') + '-' + (parseInt(firstDay_td.attr('data-month'),10) + 1) + '-' +firstDay_td.find('a').html()).format('YYYY-MM-DD'),
                startDate: '2015-06-01',
                endDate: moment(lastDay_td.attr('data-year') + '-' + (parseInt(lastDay_td.attr('data-month'),10) + 1) + '-' +lastDay_td.find('a').html()).format('YYYY-MM-DD'),
                showTask: 1,
                isFinish: 0,
                userId: opt.userId
            }).done(function (json) {
                if (json.status === 0) {
                    var dateArray = [];
                    $.each($.parseJSON(json.data), function (key,value) {
                        dateArray.push(new Date(key));
                    });
                    me._scheduleDate = dateArray;
                    elem.find('div[act=ambassadorDatePicker]').datepicker('mark',  me._scheduleDate);
                } else {
                    $.msg(rk.i18n('LOAD_ERROR'));
                }
            });

        },
        _renderSelectedTips: function(){
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var selectDateStr = '';
            for(var i=0;i<me._selectedDate.length;i++){
                if(opt.calendarType === 'week'){
                    selectDateStr += weekMap[me._selectedDate[i]];
                }else{
                    selectDateStr += me._selectedDate[i];
                }

                if(i < me._selectedDate.length - 1){
                    selectDateStr += ',';
                }
            }
            if(selectDateStr === ''){
                elem.find('.schedule-datepicker-select-date').hide();
            }else{
                elem.find('.schedule-datepicker-select-date').show();
                elem.find('span[act=select-date]').html(selectDateStr);
            }
        },
        _renderWeek: function(){
            var me = this;
            var elem = me.element;
            var opt = me.options;

            elem.append('<div class="schedule-datepicker-select-date"><span>计划将于</span><span act="select-date"></span><span>重复</span></div>') ;
            elem.append('<div act="ambassadorWeekPicker" class="ambassador-datepicker"><ul class="week-list"></ul></div>');
            var scheduleDatePicker = elem.find('div[act=ambassadorWeekPicker] > ul');
            var weeks = ['',rk.i18n('SCHEDULE_FULL_MONDAY'),rk.i18n('SCHEDULE_FULL_TUESDAY'),rk.i18n('SCHEDULE_FULL_WEDNESDAY'),rk.i18n('SCHEDULE_FULL_THURSDAY'),rk.i18n('SCHEDULE_FULL_FRIDAY'),rk.i18n('SCHEDULE_FULL_SATURDAY'),rk.i18n('SCHEDULE_FULL_SUNDAY')];
            for(var i=1;i<8;i++){
                var ifChecked = "";
                if($.inArray(i,me._selectedDate) >= 0){
                    ifChecked = "checked";
                }
                scheduleDatePicker.append('<li class="week-item"><span class="ui-check-buttonset"><input type="checkbox" class="accordion-ck" id="day'+i+'" '+ifChecked+'/><label for="day'+i+'">'+weeks[i]+'</label></span></li>');
            }


            elem.find('.accordion-ck').each(function(){
                    var ck = $(this);
                    ck.button();

                    if(ck[0].checked){
                        ck.next().find('span').css('color','#2898e0');
                    }

                    ck.click(function(){
                        var day = parseInt(ck.attr('id').slice(3),10);
                        if(ck[0].checked){
                            me._selectedDate.push(day);
                            me._selectedDate = me._selectedDate.sort(function(a,b){
                                return a > b;
                            });
                            ck.next().find('span').css('color','#2898e0');
                            if(!opt.multiSelect && me._selectedDate.length === 1){
                                 elem.find('.accordion-ck').each(function(){
                                    $(this).attr('disabled',true);
                                 });
                                 ck.removeAttr('disabled');
                            }
                        }else{
                            var index = $.inArray(day, me._selectedDate);
                            if(index >= 0){
                                me._selectedDate.splice(index,1);
                            }
                            ck.next().find('span').css('color','#000000');
                            if(!opt.multiSelect){
                                 elem.find('.accordion-ck').each(function(){
                                    $(this).removeAttr('disabled',true);
                                 });
                            }
                        }
                        me._renderSelectedTips();
                    });
                });

            elem.find('.schedule-datepicker-select-date').hide();
        },
        _renderMonth: function(){
            var me = this;
            var elem = me.element;
            var opt = me.options;

            elem.append('<div class="schedule-datepicker-select-date"><span>计划将于每月</span><span act="select-date"></span><span>日重复</span></div>') ;
            elem.append('<div act="ambassadorMonthPicker" class="ambassador-datepicker"></div>');
            var scheduleDatePicker = elem.find('div[act=ambassadorMonthPicker]');
            scheduleDatePicker.datepicker({
                showOtherMonths: false,
                selectOtherMonths: false,
                changeMonth: false,
                changeYear: false,
                defaultDate: '2014-12-01',
                dayNamesMin:['','','','','','',''],
                beforeShowDay: function(date){
                    var theDay = parseInt(moment(date).format("D"),10);
                    return [true,$.inArray(theDay,me._selectedDate) >= 0?"ui-state-selected":''];
                },
                onSelect:function(){
                    var date = scheduleDatePicker.datepicker('getDate');
                    var day = parseInt(moment(date).format('D'),10);
                    var index = $.inArray(day, me._selectedDate);
                    if(index >= 0){
                        me._selectedDate.splice(index,1);
                        scheduleDatePicker.datepicker('setDate','2014-12-01');
                    }else{
                        if(opt.multiSelect || me._selectedDate.length < 1){
                            me._selectedDate.push(day);
                            me._selectedDate = me._selectedDate.sort(function(a,b){
                                return a > b;
                            });
                        }else if(!opt.multiSelect){
                            me._selectedDate = [];
                            me._selectedDate.push(day);
                        }
                    }
                    me._renderSelectedTips();
                }   
            });

            elem.find('.schedule-datepicker-select-date').hide();
        },
        destory: function(){
            var me = this;
            var elem = me.element;
            var opt = me.options;

            elem.empty();
            me._selectedDate = [];
            me._scheduleDate = [];
            //$.Widget.prototype.destroy.apply(me);
        }
    });
});